package org.jradweb.core.taglib;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;

import org.jradweb.core.controller.JMultiActionController;
import org.jradweb.core.orm.PageResult;
import org.springframework.beans.BeansException;

public class PageNavigateTag extends BaseTag {

	private Integer pageNumber;
	private Integer totalPage;
	
	
	private static String PAGE_FIRST = "form.page.first";
	private static String PAGE_PREVIOUS = "form.page.previous";
	private static String PAGE_NEXT = "form.page.next";
	private static String PAGE_LAST = "form.page.last";
	private static String PAGE_JUMP_TO = "form.page.jumpTo";
	private static String PAGE_PAGE_INFO = "form.page.pageInfo";
	private static String PAGE_PAGE_PAGE = "form.page.page";
	private static String PAGE_PAGE_INVALID_PAGE_NUMBER = "form.page.invalidPageNumber";
	
	private PageResult pageResult;
	
	
	public PageResult getPageResult() {
		return pageResult;
	}

	public void setPageResult(PageResult pageResult) {
		this.pageResult = pageResult;
		this.pageNumber=pageResult.getPageNumber();
		this.totalPage=pageResult.getPageCount();
	}

	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
		String queryString = req.getQueryString();

		Locale locale = req.getLocale();
		ResourceBundle rb = ResourceBundle.getBundle("messages", locale);

		String first = rb.getString(PAGE_FIRST);
		String previous = rb.getString(PAGE_PREVIOUS);
		String next = rb.getString(PAGE_NEXT);
		String last = rb.getString(PAGE_LAST);
		String jumpTo = rb.getString(PAGE_JUMP_TO);
		String pageInfo = rb.getString(PAGE_PAGE_INFO);
		String page = rb.getString(PAGE_PAGE_PAGE);
		String invalidPageNumber=rb.getString(PAGE_PAGE_INVALID_PAGE_NUMBER);

		MessageFormat fm = new MessageFormat(pageInfo);
		String currentPageInfo = fm.format(new Integer[] { pageNumber,
				totalPage });
		String contextPath = req.getContextPath();
		String servletPath = req.getRequestURI();
		String url = (String) req
				.getAttribute(JMultiActionController.REQUEST_URL);

		StringBuffer sb = new StringBuffer();
		BodyContent bc = this.getBodyContent();
		try {
			if(totalPage!=null&&totalPage>1)
			{
			sb.append("<script language=\"javascript\">\n	function jumpToPage(totalPage){\n");
			sb
					.append(" var pageValue=document.getElementById(\"goto_page_input_form\").value;\n");
			sb.append("var pageNumber=parseInt(pageValue);\n");
			sb.append("if(isNaN(pageNumber)) {alert('"+invalidPageNumber+"');return;}\n");
			sb.append("else if(pageNumber<=0){alert('"+invalidPageNumber+"');return;}\n");
			sb.append("else if(pageNumber>totalPage){alert('"+invalidPageNumber+"');return;}\n");
			sb.append("else {var url=\"").append(getPageUri(url, queryString)).append("\";\n");
			sb.append("window.location.href=url+pageNumber;}}\n</script>");
			
			sb.append("<span class=\"start\"><a href=\"").append(getPageUri(url, queryString)).append(
					"1\">").append(first).append("</a></span>&nbsp;");
			sb.append("<span class=\"previous\"><a href=\"").append(getPageUri(url, queryString))
					.append(
							pageNumber <= 1 ? 1 : (pageNumber - 1)).append(
							"\">").append(previous).append("</a></span>&nbsp;");
			sb.append(currentPageInfo).append("&nbsp;");
			sb.append("<span class=\"next\"><a href=\"").append(getPageUri(url, queryString)).append(
					pageNumber < totalPage ? (pageNumber + 1) : totalPage)
					.append("\">").append(next).append("</a></span>&nbsp;");
			sb.append("<span class=\"end\"><a href=\"").append(getPageUri(url, queryString)).append(totalPage).append("\">").append(last)
					.append("</a></span>&nbsp;");
			sb
					.append(jumpTo)
					.append(
							"<input id=\"goto_page_input_form\" onkeydown=\"javascript:if(event.keyCode==13){jumpToPage("
									+ totalPage
									+ ")}\" name=\"page\" class=\"input_mini\" value=\"")
					.append("").append("\">").append(page).append("");
			}
			else
			{
				sb.append("&nbsp;");
			}
			this.pageContext.getOut().write(sb.toString());
			return super.doEndTag();
		} catch (BeansException e) {
			throw new JspException(e);
		} catch (IOException e) {
			throw new JspException(e);
		}
	}

	private String getPageUri(String url, String queryString) {
		if (queryString == null) {
			return url + "?page=";
		}
		else{
			if(queryString.indexOf("page=")>=0){
				String[] ps= queryString.split("&");
				
				StringBuffer sb=new StringBuffer(url);
				boolean added=false;
				for(int i=0;i<ps.length;i++)
				{
					String p=ps[i];
					if(p.indexOf("page=")<0){
						if(i==0){
							sb.append("?").append(p);
							added=true;
						}
						else{
							sb.append("&").append(p); 
						}
					}
				}
				if(added){
					return sb.append("&page=").toString();
				}
				else{
					return sb.append("?page=").toString();
				}
			}
			return url + "?" + queryString + "&page=";
		}
	}



	public static void main(String[] args) {
		String pattern = "（第 {0} 页  共 {1} 页）";
		MessageFormat mf = new MessageFormat(pattern);
		String result = mf.format(new String[] { "1", "2" });
		System.out.println(result);
	}

}
